import chokidar from 'chokidar'
import path from 'path'
import { Logger } from './logger.js'
import { loadPlugins, scheduledJobs } from './pluginLoader.js'
import { createServer, port } from './server.js'
import { __dirname } from '../../../components/Path.js'

export const logger = new Logger(port)

class Start {
  constructor () {
    this.logger = logger
    const { app, listener } = createServer(this.logger)
    this.app = app
    this.listener = listener
    // this.setupWatcher();
  }

  setupWatcher () {
    const watcher = chokidar.watch(path.join(__dirname, 'plugins'), {
      ignored: /(^|[\/\\])\../,
      persistent: true
    })

    watcher.on('change', async () => {
      this.logger.logWithPort(
        'info',
        '[ad-api]',
        '插件目录发生改变，正在重新加载...'
      )

      Object.keys(scheduledJobs).forEach((pluginFolderName) => {
        const jobs = scheduledJobs[pluginFolderName]
        if (jobs) {
          jobs.forEach((job) => job?.cancel && job.cancel())
          delete scheduledJobs[pluginFolderName]
          this.logger.logWithPort(
            'info',
            '[ad-api]',
            `定时任务 ${pluginFolderName} 已取消`
          )
        }
      })

      this.logger.logWithPort('info', '[ad-api]', '所有定时任务处理完毕')

      await new Promise((resolve) => this.listener.close(resolve))

      this.app._router.stack = this.app._router.stack.filter(
        (route) => !route.route || !route.route.path.startsWith('/api/')
      )

      loadPlugins(this.app, path.join(__dirname, 'plugins'), this.logger)
    })
  }
}

export default Start
